import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/widget/base_get_builder.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/utils/utils_time.dart';
import 'package:flutter_09_game/widgets/appbar/common_app_bar.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/button/debounce_gesture_detector.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/pages/profile/widgets/safety_score_animation_widget.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'profile_safety_center_logic.dart';

class ProfileSafetyCenterPage extends StatelessWidget {
  ProfileSafetyCenterPage({super.key});

  final ProfileSafetyCenterLogic logic = Get.put(ProfileSafetyCenterLogic());

  @override
  Widget build(BuildContext context) {
    return BaseGetBuilder<ProfileSafetyCenterLogic>(
      appBar: CommonAppBar(
        title: LocaleKeys.securityCenter.tr,
        actions: [
          // GestureDetector(
          //   onTap: () {
          //     AppUserManager().showServiceSheet();
          //   },
          //   child: AutoImage(
          //     Assets.commonServiceBtn,
          //     width: 32.w,
          //   ),
          // ),
          // 10.horizontalSpace,
        ],
      ),
      builder: (l) {
        return Obx(() {
          return SingleChildScrollView(
            padding:
                EdgeInsets.only(bottom: 16.w + ScreenUtil().bottomBarHeight),
            // .copyWith(bottom: 16.w + ScreenUtil().bottomBarHeight),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                      color: AppColor.navBgColor,
                      borderRadius: BorderRadius.only(
                          bottomRight: Radius.circular(30.w),
                          bottomLeft: Radius.circular(30.w))),
                  // height: 300,
                  child: Column(
                    children: [
                      16.verticalSpaceFromWidth,
                      Center(
                        child: Obx(() {
                          return SafetyScoreAnimationWidget(
                            safetyScore: min(
                                AppUserManager().user.value?.safetyScore ?? 0,
                                100),
                            size: 240,
                            strokeWidth: 8,
                          );
                        }),
                      ),
                      16.verticalSpaceFromWidth,
                      Row(
                        children: [
                          Expanded(
                              child: _builtHeaderBtn(
                                  LocaleKeys.lastLoginIp.tr,
                                  AppUserManager().user.value?.lastLoginIp ??
                                      '')),
                          8.horizontalSpace,
                          Expanded(
                              child: _builtHeaderBtn(
                                  LocaleKeys.lastLoginTime.tr,
                                  UtilsTime.ymdFormatTime(AppUserManager()
                                          .user
                                          .value
                                          ?.lastLoginAt ??
                                      ''))),
                        ],
                      ),
                      24.verticalSpaceFromWidth,
                    ],
                  ),
                ),
                16.verticalSpaceFromWidth,
                Text(
                  LocaleKeys.operations.tr,
                  style: TextStyle(
                    color: AppColor.textPrimary.withOpacity(0.94),
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                ).marginOnly(left: 16.w),
                24.verticalSpaceFromWidth,
                Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: Column(
                      children: [
                        _buildSafetyItem(
                            iconPath: Assets.profileSafetyItemManager,
                            title: LocaleKeys.accountManagement.tr,
                            infoStr: LocaleKeys.bindBettingAddress.tr,
                            isBound: AppUserManager()
                                .user
                                .value
                                ?.hasBindTrc20Address,
                            point: 35,
                            onClick: () {
                              if (AppUserManager()
                                      .user
                                      .value
                                      ?.hasSetSecurityQuestion !=
                                  true) {
                                Get.toNamed(AppRoutes.profileSetPasswordPage);
                              } else {
                                if (AppUserManager()
                                        .user
                                        .value
                                        ?.hasBindTrc20Address !=
                                    true) {
                                  Get.toNamed(AppRoutes.profileBindAddressPage);
                                } else {
                                  Get.toNamed(AppRoutes.profileTrcManagerPage);
                                }
                              }
                            }),
                        _buildSafetyItem(
                            iconPath: Assets.profileSafetyItemEdit,
                            title: LocaleKeys.changeFundPassword.tr,
                            infoStr: LocaleKeys.setFundPasswordDesc.tr,
                            isBound:
                                AppUserManager().user.value?.hasSetFundPassword,
                            point: 20,
                            onClick: () {
                              if (AppUserManager()
                                      .user
                                      .value
                                      ?.hasSetFundPassword !=
                                  true) {
                                Get.toNamed(AppRoutes.profileSetPasswordPage);
                              } else {
                                Get.toNamed(
                                    AppRoutes.profileEditFundPasswordPage);
                              }
                            }),
                        _buildSafetyItem(
                            iconPath: Assets.profileSafetyItemSecurity,
                            title: LocaleKeys.setSecurityQuestion.tr,
                            infoStr: LocaleKeys.setSecurityQuestionDesc.tr,
                            isBound: AppUserManager()
                                .user
                                .value
                                ?.hasSetSecurityQuestion,
                            point: 10,
                            onClick: () {
                              if (AppUserManager()
                                      .user
                                      .value
                                      ?.hasSetSecurityQuestion !=
                                  true) {
                                Get.toNamed(AppRoutes.profileSetPasswordPage);
                              } else {
                                Get.toNamed(
                                    AppRoutes.profileEditSecurityQuestionPage);
                              }
                            }),
                        _buildSafetyItem(
                            iconPath: Assets.profileSafetyItemLogin,
                            title: LocaleKeys.changeLoginPassword.tr,
                            infoStr: LocaleKeys.changeLoginPasswordDesc.tr,
                            // isBound: AppUserManager().user.value?.hasBindTrc20Address ,
                            // point: 20,
                            onClick: () {
                              if (AppUserManager()
                                      .user
                                      .value
                                      ?.hasSetFundPassword !=
                                  true) {
                                Get.toNamed(AppRoutes.profileSetPasswordPage);
                              } else {
                                Get.toNamed(
                                    AppRoutes.profileEditLoginPasswordPage);
                              }
                            }),
                        // 12.verticalSpaceFromWidth,
                        _buildSafetyItem(
                            iconPath: Assets.profileSafetyItemVersion,
                            title: LocaleKeys.currentVersion.tr,
                            infoStr: 'V${AppConfig.version}',
                            // isBound: AppUserManager().user.value?.hasBindTrc20Address ,
                            // point: 20,
                            onClick: () {
                              UtilsOther().getAppPackage(isLoading: true);
                            }),
                        12.verticalSpaceFromWidth,
                        CommonButton.expend(
                          title: LocaleKeys.logout.tr,
                          textColor: AppColor.gameResultEven,
                          enable: false,
                          alwaysCanClick: true,
                          onClick: () {
                            clickLogoutDialog();
                          },
                        ),
                      ],
                    ))
              ],
            ),
          );
        });
      },
    );
  }

  Widget _builtHeaderBtn(String title, String indoStr) {
    return Container(
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: AppColor.color2D2F35,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              color: AppColor.textPrimary.withOpacity(0.7),
              fontSize: 12.sp,
            ),
          ),
          12.verticalSpaceFromWidth,
          Text(
            indoStr,
            style: TextStyle(
                color: AppColor.textPrimary.withOpacity(0.94),
                fontSize: 12.sp,
                fontWeight: FontWeight.w900),
          ),
        ],
      ),
    );
  }

  // // 构建安全功能列表
  // Widget _buildSafetyItemsList() {
  //   return Column(
  //     children: List.generate(
  //       logic.safetyItems.length,
  //           (index) => _buildSafetyItem(logic.safetyItems[index], index),
  //     ),
  //   );
  // }

  // 构建安全功能项目
  Widget _buildSafetyItem({
    required String iconPath,
    required String title,
    required String infoStr,
    int? point,
    bool? isBound,
    required Function onClick,
  }) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.w),
      child: DebounceGestureDetector(
        onTap: () {
          onClick.call();
        },
        child: Container(
          padding: EdgeInsets.all(12.w),
          decoration: BoxDecoration(
            color: AppColor.navBgColor,
            borderRadius: BorderRadius.circular(12.w),
          ),
          child: Row(
            children: [
              AutoImage(
                iconPath,
                width: 44.w,
              ),
              // _buildIconContainer(item.icon),
              16.horizontalSpace,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: TextStyle(
                        color: AppColor.textPrimary.withOpacity(0.94),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    4.verticalSpaceFromWidth,
                    Text(
                      infoStr,
                      style: TextStyle(
                        color: AppColor.textPrimary.withOpacity(0.5),
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),
              Visibility(
                  visible: (point ?? 0) > 0,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        '+$point',
                        style: TextStyle(
                          color: AppColor.primary,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w900,
                        ),
                      ),
                      4.verticalSpaceFromWidth,
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          // if (item.isBound) ...[
                          AutoImage(
                            isBound == true
                                ? Assets.commonCircleCorrect
                                : Assets.commonCircleError,
                            width: 10.w,
                            height: 10.w,
                            // color: AppColor.primarySecondary,
                          ),
                          4.horizontalSpace,
                          // ],
                          Text(
                            title == LocaleKeys.accountManagement.tr
                                ? (isBound == true
                                    ? LocaleKeys.bound.tr
                                    : LocaleKeys.notBound.tr)
                                : (isBound == true
                                    ? LocaleKeys.alreadySet.tr
                                    : LocaleKeys.notSet.tr),
                            style: TextStyle(
                              color: isBound == true
                                  ? AppColor.homePrizePoolIndicator
                                  : AppColor.gameResultEven,
                              fontSize: 10.sp,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                    ],
                  )),

              4.horizontalSpace,
              // _buildArrowIcon(),
              AutoImage(
                Assets.gameArrowRight,
                width: 24.w,
              )
            ],
          ),
        ),
      ),
    );
  }

  clickLogoutDialog() {
    // if (AppUserManager().user.value?.hasSetFundPassword != true) {
    CommonNormalSheet(
            title: LocaleKeys.warmTips.tr,
            child: Column(
              children: [
                AutoImage(
                  Assets.commonMineLogout,
                  width: 80.w,
                ),
                32.verticalSpaceFromWidth,
                Text(
                  LocaleKeys.logoutConfirm.tr,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: AppColor.textPrimary.withOpacity(0.7),
                      fontSize: 14.sp),
                ),
                24.verticalSpaceFromWidth,
                Row(
                  children: [
                    Expanded(
                        child: CommonButton(
                      title: LocaleKeys.later.tr,
                      fontSize: 14.sp,
                      enable: false,
                      alwaysCanClick: true,
                      onClick: () {
                        Get.back();
                      },
                    )),
                    8.horizontalSpace,
                    Expanded(
                        child: CommonButton(
                      title: LocaleKeys.ok.tr,
                      fontSize: 14.sp,
                      onClick: () {
                        Get.back();
                        AppUserManager().logout();
                        Future.delayed(const Duration(milliseconds: 400), () {
                          Get.toNamed(AppRoutes.loginPage);
                        });

                        // Get.toNamed(AppRoutes.profileSetPasswordPage);
                      },
                    )),
                  ],
                ),
                16.verticalSpaceFromWidth,
              ],
            ).marginSymmetric(horizontal: 16.w))
        .show();
  }
// }
}
